﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using FeedReader.Shared.Extensions.OPML;

namespace FeedReader.Shared.Data
{
    public class OPMLReader
    {
        XmlDocument thedoc;
        private List<OPMLItem> items = new List<OPMLItem>();

        private OPMLReader(XmlDocument newdoc)
        {
            thedoc = newdoc;
            parseitems();
        }
        private void parseitems()
        {
            XmlNode bodynode = thedoc.DocumentElement.ChildNodes[1];

            var result = from XmlNode x in bodynode.ChildNodes
                         where x.Attributes.Count >1
                         select (new OPMLItem()).ParseItem(x);


            this.items = result.ToList<OPMLItem>();

        }
        public IQueryable<OPMLItem> Items()
        {
            return items.AsQueryable<OPMLItem>();
        }

        public static OPMLReader CreateFromString(string text)
        {
            XmlDocument mydoc = new XmlDocument();

            mydoc.LoadXml(text);

            return new OPMLReader(mydoc);
        }
        public static OPMLReader Create(string server)
        {
            XmlDocument mydoc = new XmlDocument();

            mydoc.Load(server);

            return new OPMLReader(mydoc);
        }
        public static OPMLReader Create(Stream thestream)
        {
            XmlReader thereader = XmlReader.Create(thestream);

            XmlDocument mydoc = new XmlDocument();

            mydoc.Load(thereader);

            return new OPMLReader(mydoc);
        }
    }
}
